// This file is part of OpenTSDB.
// Copyright (C) 2017 TeleDB Development Group.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version.  This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
// General Public License for more details.  You should have received a copy
// of the GNU Lesser General Public License along with this program.  If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.utils;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class DigestUtil {
    private static final Logger log = LoggerFactory.getLogger(DigestUtil.class);
    private static final String DEFAULT_ENCODE = "UTF-8";
    private static final String DEFAULT_KEY = "ctg-tsdb1234#!@";

    public static String encryptAes(String sSrc) {
        return encrypt(sSrc, "AES");
    }

    public static String decryptAes(String sSrc) {
        return decrypt(sSrc, "AES");
    }

    public static String encryptDes(String sSrc) {
        return encrypt(sSrc, "DES");
    }

    public static String decryptDes(String sSrc) {
        return decrypt(sSrc, "DES");
    }

    public static String encrypt(String sSrc, String algorithm) {
        return encrypt(sSrc, algorithm, DEFAULT_KEY);
    }

    public static String decrypt(String sSrc, String algorithm) {
        return decrypt(sSrc, algorithm, DEFAULT_KEY);
    }

    public static String encrypt(String sSrc, String algorithm, String key) {
        try {
            Cipher cipher = buildCipher(Cipher.ENCRYPT_MODE, algorithm, key);
            if (cipher == null) {
                return sSrc;
            }
            byte[] result = cipher.doFinal(sSrc.getBytes(DEFAULT_ENCODE));
            return Base64.getEncoder().encodeToString(result);
        } catch (Exception e) {
            log.error(algorithm + "加密异常", e);
        }
        return sSrc;
    }

    public static String decrypt(String sSrc, String algorithm, String key) {
        try {
            Cipher cipher = buildCipher(Cipher.DECRYPT_MODE, algorithm, key);
            if (cipher == null) {
                return sSrc;
            }
            byte[] result = cipher.doFinal(Base64.getDecoder().decode(sSrc));
            return new String(result, DEFAULT_ENCODE);
        } catch (IllegalArgumentException | BadPaddingException | IllegalBlockSizeException | UnsupportedEncodingException e) {
            log.error(algorithm + "解密异常");
        }
        return sSrc;
    }

    private static Cipher buildCipher(int aesMode, String algorithm, String key) {
        Cipher cipher = null;
        switch (algorithm) {
            case "AES":
                cipher = buildAesCipher(aesMode, key);
                break;
            /*case "DES":
                cipher = buildDesCipher(aesMode, key);
                break;*/
        }
        return cipher;
    }

    private static Cipher buildAesCipher(int aesMode, String key) {
        Cipher cipher = null;
        try {
            //1.生成key
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key.getBytes(DEFAULT_ENCODE));
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] keyBytes = secretKey.getEncoded();
            //2.key的转换
            Key secretKeySpec = new SecretKeySpec(keyBytes, "AES");
            //3.加密
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(aesMode, secretKeySpec);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | UnsupportedEncodingException | InvalidKeyException e) {
            log.error("AES Cipher获取失败", e);
        }
        return cipher;
    }


    public static void main(String[] args) {
        System.out.println(encryptAes("ctyun-tsdb@123"));
        System.out.println(decryptAes(encryptAes("ctyun-tsdb@123")));
    }
}
